﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using CooStationsToolsNew.Model;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Documents;
using System.Windows.Shapes;
using System.Windows;
using System.Data;
using System.Windows.Media;
using System.Windows.Input;
using System.Globalization;

namespace CooStationsToolsNew
{
    class ModelTools
    {
        ProjectTools pt = new ProjectTools();
       // public static AdornerLayer layer;//= AdornerLayer.GetAdornerLayer(canvas);
       // public static MyCanvasAdorner myCan;
       // public static Image pessImg = null;
       // public static Rectangle pessRect = null;
       // public static Canvas targetCan = null;
      //  public static Canvas pessCan = null;
        public static TextBlock pessText = null;
        public static String isStyle = null;
        Canvas pcan;
        public static AutoSizeRichTextBox autoRTB = null;
        public static String acStyle = null;
        public static double _x, _y, _imgx, _imgy;
        public static string Press_name;
        public static List<UIElement> listUI = new List<UIElement>();
        public static double objAlpha;
        public ModelTools()
        {
        }
        /// <summary>
        /// 随即ID
        /// </summary>
        /// <returns></returns>
        public string GetRandom()
        {
            string guid = Guid.NewGuid().ToString();
            int n = guid.IndexOf("-");
            return guid.Substring(0, n);
        }
        /// <summary>
        /// 将Color转换成字符串
        /// </summary>
        /// <param name="_color"></param>
        /// <returns></returns>
        public string ColorToHex(System.Drawing.Color _color)
        {
            return "0x" + String.Format("{0:X}", System.Drawing.Color.FromArgb(_color.R, _color.G, _color.B).ToArgb()).Substring(2);
        }
        /// <summary>
        /// 将字符串转换为Color
        /// </summary>
        /// <param name="color">带#号的16进制颜色</param>
        /// <returns></returns>
        public static System.Windows.Media.Color ToColor(string color)
        {
            System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml(color);
            byte alpha = col.A;
            byte red = col.R;
            byte green = col.G;
            byte blue = col.B;
            return System.Windows.Media.Color.FromArgb(alpha, red, green, blue);
        }
        /// <summary>
        /// 将一个图片保存到TEMPXML中
        /// </summary>
        /// <param name="pic"></param>
        internal void addImgtoxml(Pic pic, string canvas)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(App.appPath + "\\temp\\" + App.pageName + ".xml");
            XmlNode root = doc.ChildNodes[1];
            XmlElement xe2 = doc.CreateElement("img");//创建一个<item>节点 
            FileInfo f = new FileInfo(pic.Url);
            xe2.SetAttribute("name", pic.Name);
            xe2.SetAttribute("url", "pic/" + f.Name);
            xe2.SetAttribute("x", pic.X.ToString());
            xe2.SetAttribute("y", pic.Y.ToString());
            xe2.SetAttribute("width", pic.Width.ToString());
            xe2.SetAttribute("height", pic.Height.ToString());
            xe2.SetAttribute("alpha", pic.Alpha.ToString());
            xe2.SetAttribute("id", pic.Id);

            if (canvas == "work")
            {
                root.AppendChild(xe2);
            }
            else
            {
                AddControlToXml(doc.ChildNodes[1].ChildNodes, canvas, xe2);
            }

            doc.Save(App.appPath + "\\temp\\" + App.pageName + ".xml");
        }
        /// <summary>
        /// 将一个形状保存到TEMPXML
        /// </summary>
        /// <param name="re"></param>
        internal void addRecttoxml(Model.Rect re, string canvas)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(App.appPath + "\\temp\\" + App.pageName + ".xml");
            XmlNode root = doc.ChildNodes[1];
            XmlElement xe2 = doc.CreateElement("rect");//创建一个<item>节点 
            xe2.SetAttribute("id", re.Id);
            xe2.SetAttribute("name", re.Name);
            xe2.SetAttribute("x", re.X.ToString());
            xe2.SetAttribute("y", re.Y.ToString());
            xe2.SetAttribute("width", re.Width.ToString());
            xe2.SetAttribute("height", re.Height.ToString());
            xe2.SetAttribute("rectAlpha", re.RectAlpha.ToString());
            xe2.SetAttribute("rectColor", re.RectColor);
            xe2.SetAttribute("lineColor", re.LineColor);
            xe2.SetAttribute("lineAlpha", re.LineAlpha.ToString());
            xe2.SetAttribute("border", re.Border.ToString());

            if (canvas == "work")
            {
                root.AppendChild(xe2);
            }
            else
            {
                AddControlToXml(doc.ChildNodes[1].ChildNodes, canvas, xe2);
            }

            doc.Save(App.appPath + "\\temp\\" + App.pageName + ".xml");
        }
        /// <summary>
        /// 层增加到xml
        /// </summary>
        /// <param name="re"></param>
        /// <param name="canvas"></param>
        public void addDivtoxml(Div re, string canvas)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(App.appPath + "\\temp\\" + App.pageName + ".xml");
            XmlNode root = doc.ChildNodes[1];

            XmlElement xe2 = doc.CreateElement("div");//创建一个<item>节点 
            xe2.SetAttribute("id", re.Id);
            xe2.SetAttribute("name", re.Name);
            xe2.SetAttribute("x", re.X.ToString());
            xe2.SetAttribute("y", re.Y.ToString());
            xe2.SetAttribute("width", re.Width.ToString());
            xe2.SetAttribute("height", re.Height.ToString());
            xe2.SetAttribute("alpha", re.Alpha.ToString());
            if (canvas == "work")
            {
                root.AppendChild(xe2);
            }
            else
            {
                AddControlToXml(doc.ChildNodes[1].ChildNodes, canvas, xe2);
            }
            doc.Save(App.appPath + "\\temp\\" + App.pageName + ".xml");
        }

        public void ClearObj()
        {
            pessText = null;
        }
        /// <summary>
        /// 文本增加到XML
        /// </summary>
        /// <param name="text"></param>
        /// <param name="canvas"></param>
        public void addTexttoxml(Text text,string canvas)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(App.appPath + "\\temp\\" + App.pageName + ".xml");
            XmlNode root = doc.ChildNodes[1];
            XmlElement xe2 = doc.CreateElement("text");//创建一个<item>节点 
            xe2.SetAttribute("id", text.Id);
            xe2.SetAttribute("name", text.Name);
            xe2.SetAttribute("x", text.X.ToString());
            xe2.SetAttribute("y", text.Y.ToString());
            xe2.SetAttribute("width", text.Width.ToString());
            xe2.SetAttribute("height", text.Height.ToString());

            if (text.Align != null && text.Align !="")
            {
                xe2.SetAttribute("align", text.Align);
            }
            if (text.Html != null && text.Html != "")
            {
                xe2.SetAttribute("html", text.Html);
            }
            if (text.Bold != null && text.Bold != "")
            {
                xe2.SetAttribute("bold", text.Bold);
            }
            if (text.Size != null && text.Size != "")
            {
                xe2.SetAttribute("size", text.Size);
            }
            if (text.Color != null && text.Color != "")
            {
                xe2.SetAttribute("color", text.Color);
            }
            if (text.WordWrap != null && text.WordWrap != "")
            {
                xe2.SetAttribute("wordWrap", text.WordWrap);
            }
            if (text.Multiline != null && text.Multiline != "")
            {
                xe2.SetAttribute("multiline", text.Multiline);
            }
            XmlElement xe3 = doc.CreateElement("value");//创建一个<item>节点 

            xe3.InnerXml = "<![CDATA["+ text.Content + "]]>";
            xe2.AppendChild(xe3);
            if (canvas == "work")
            {
                root.AppendChild(xe2);
            }
            else
            {
                AddControlToXml(doc.ChildNodes[1].ChildNodes, canvas, xe2);
            }
            doc.Save(App.appPath + "\\temp\\" + App.pageName + ".xml");
        }

        /// <summary>
        /// 递归增加到xml
        /// </summary>
        /// <param name="xmlnl"></param>
        /// <param name="parent"></param>
        /// <param name="xe2"></param>
        private void AddControlToXml(XmlNodeList xmlnl, string parent, XmlElement xe2)
        {
            foreach (XmlNode xn in xmlnl)
            {
                if (xn.Name == "value")
                {
                    return;
                }
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("name") == parent)
                {
                    xn.AppendChild(xe2);
                    break;
                }
                if (xe.HasChildNodes == false)
                {
                    if (xe.GetAttribute("name") == parent)
                    {
                        xn.AppendChild(xe2);
                    }

                }
                else
                {
                    AddControlToXml(xe.ChildNodes, parent, xe2);

                }

            }
        }
        /// <summary>
        /// 将保存好的IMG存储到DataTable
        /// </summary>
        /// <param name="ob"></param>
        public bool SaveToImageData(Image ob, DataTable dt)
        { bool flag=true;
            try
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "image")
                    {
                        Pic im = (Pic)dt.Rows[i][1];
                        if (ob != null && im.Name == ob.Name)
                        {
                            im.Id = ob.Uid;
                            im.X = Convert.ToInt32(ob.GetValue(Canvas.LeftProperty));
                            im.Y = Convert.ToInt32(ob.GetValue(Canvas.TopProperty));
                            im.Width = Convert.ToInt32(ob.Width);
                            im.Height = Convert.ToInt32(ob.Height);
                            if (ob.Opacity == 100)
                            {
                                im.Alpha = Convert.ToInt32(ob.Opacity);
                            }
                            else
                            {
                                im.Alpha = Convert.ToInt32(ob.Opacity * 100);
                            }
                            try
                            {
                                FileInfo f = new FileInfo(ob.Source.ToString().Substring(8));
                                im.Url = "pic/" + f.Name;
                            }
                            catch (Exception)
                            {
                            }

                            dt.Rows[i][1] = im;
                            App.piclist.RemoveAt(App.piclist.IndexOf(ob));
                            App.piclist.Add(ob);
                            pt.SaveToXml(im, App.appPath + "\\temp\\" + App.pageName + ".xml");
                            break;
                        }
                    }
                    if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        SaveToImageData(ob, div.Dt);
                    }
                }
            }
            catch {
                flag = false;
            } 
            return flag;
        }
        /// <summary>
        /// 将保存好的RECT存储到DataTable
        /// </summary>
        /// <param name="rectangle"></param>
        /// <param name="dataTable"></param>
        public bool SaveToRectData(System.Windows.Shapes.Rectangle rectangle, DataTable dt)
        {
            bool flag = true;
            try
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "rect")
                    {
                        CooStationsToolsNew.Model.Rect re = (CooStationsToolsNew.Model.Rect)dt.Rows[i][1];
                        if (rectangle != null && re.Name == rectangle.Name)
                        {
                            re.Id = rectangle.Uid;
                            re.X = Convert.ToInt32(rectangle.GetValue(Canvas.LeftProperty));
                            re.Y = Convert.ToInt32(rectangle.GetValue(Canvas.TopProperty));
                            re.Width = Convert.ToInt32(rectangle.Width);
                            re.Height = Convert.ToInt32(rectangle.Height);
                            if (rectangle.Opacity == 100)
                            {
                                re.RectAlpha = Convert.ToInt32(rectangle.Opacity);
                                re.LineAlpha = Convert.ToInt32(rectangle.Opacity);
                            }
                            else
                            {
                                re.RectAlpha = Convert.ToInt32(rectangle.Opacity * 100);
                                re.LineAlpha = Convert.ToInt32(rectangle.Opacity * 100);
                            }
                            re.RectColor = ColorToHex(System.Drawing.ColorTranslator.FromHtml(rectangle.Fill.ToString()));
                            re.LineColor = ColorToHex(System.Drawing.ColorTranslator.FromHtml(rectangle.Stroke.ToString()));
                            re.Border = Convert.ToInt32(rectangle.StrokeThickness);
                            dt.Rows[i][1] = re;
                            App.rectlist.RemoveAt(App.rectlist.IndexOf(rectangle));
                            App.rectlist.Add(rectangle);
                            pt.SaveToXml(re, App.appPath + "\\temp\\" + App.pageName + ".xml");
                            break;
                        }
                    }
                    if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        SaveToRectData(rectangle, div.Dt);
                    }
                }
            }
            catch {
                flag = false;
            }
            return flag;
        }
        /// <summary>
        /// 将保存好的text存储到DataTable
        /// </summary>
        /// <param name="ob"></param>
        public bool SaveToTextData(TextBlock tb, DataTable dt)
        {
            bool flag = true;
            try
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "text")
                    {
                        Text text = (Text)dt.Rows[i][1];
                        if (tb != null && text.Name == tb.Name)
                        {
                            text.Id = tb.Uid;
                            text.X = Convert.ToInt32(tb.GetValue(Canvas.LeftProperty));
                            text.Y = Convert.ToInt32(tb.GetValue(Canvas.TopProperty));
                            text.Width = Convert.ToInt32(tb.ActualWidth);
                            text.Height = Convert.ToInt32(tb.ActualHeight);
                            text.Content = tb.Text;
                            if (tb.TextAlignment == TextAlignment.Left)
                            {
                                text.Align = "left";
                            }
                            else if (tb.TextAlignment == TextAlignment.Right)
                            {
                                text.Align = "right";
                            }
                            else if (tb.TextAlignment == TextAlignment.Center)
                            {
                                text.Align = "center";
                            }
                            if (tb.FontWeight == FontWeights.Bold)
                            {
                                text.Bold = "true";
                            }
                            else if (tb.FontWeight == FontWeights.Normal)
                            {
                                text.Bold = "false";
                            }
                            text.Size = tb.FontSize.ToString();
                            text.Color = ColorToHex(System.Drawing.ColorTranslator.FromHtml(tb.Foreground.ToString()));
                            if (tb.TextWrapping == TextWrapping.Wrap)
                            {
                                text.Multiline = "true";
                            }
                            else if (tb.TextWrapping == TextWrapping.NoWrap)
                            {
                                text.Multiline = "false";
                            }

                            dt.Rows[i][1] = text;
                            App.textlist.RemoveAt(App.textlist.IndexOf(tb));
                            App.textlist.Add(tb);
                            pt.SaveToXml(text, App.appPath + "\\temp\\" + App.pageName + ".xml");
                            break;
                        }
                    }
                    if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        SaveToTextData(tb, div.Dt);
                    }
                }
            }
            catch {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 将DIV保持到数组
        /// </summary>
        /// <param name="canvas"></param>
        /// <param name="dt"></param>
        public bool SaveToDivData(Canvas canvas, DataTable dt)
        {
            bool isSave = true;
            try
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        if (canvas != null && div.Id == canvas.Uid)
                        {
                            div.Id = canvas.Uid;
                            div.X = Convert.ToInt32(canvas.GetValue(Canvas.LeftProperty));
                            div.Y = Convert.ToInt32(canvas.GetValue(Canvas.TopProperty));
                            div.Width = Convert.ToInt32(canvas.GetValue(Canvas.WidthProperty));
                            div.Height = Convert.ToInt32(canvas.GetValue(Canvas.HeightProperty));
                            if (canvas.Opacity == 100)
                            {
                                div.Alpha = Convert.ToInt32(canvas.Opacity);
                            }
                            else
                            {
                                div.Alpha = Convert.ToInt32(canvas.Opacity * 100);
                            }
                            dt.Rows[i][1] = div;
                            App.divlist.RemoveAt(App.divlist.IndexOf(canvas));
                            App.divlist.Add(canvas);
                            pt.SaveToXml(div, App.appPath + "\\temp\\" + App.pageName + ".xml");
                            isSave = true;
                            break;
                        }
                        else
                        {
                            SaveToDivData(canvas, div.Dt);
                        }
                    }
                }
            }
            catch {
                isSave = false;
            }
            return isSave;
        }

        /// <summary>
        /// 创建一个图片元素
        /// </summary>
        /// <param name="pic"></param>
        /// <param name="canvas"></param>
        public Image CreateImage(Pic pic, Canvas canvas)
        {
            if (WorkMainAreaUC.myCan != null)
            {
                WorkMainAreaUC.layer.Remove(WorkMainAreaUC.myCan);
            }
            System.Windows.Controls.Image img = new System.Windows.Controls.Image();
            pcan = canvas;
            img.Name = pic.Name;
            List<string> taglist = new List<string>();
            taglist.Add("true");
            taglist.Add("true");
            img.Tag = taglist;
            img.Uid = pic.Id;
            img.Source = new BitmapImage(new Uri(pic.Url, UriKind.RelativeOrAbsolute));
            img.Stretch = System.Windows.Media.Stretch.Fill;
            img.Width = pic.Width;
            img.Height = pic.Height;
            canvas.Children.Add(img);
            img.SetValue(Canvas.LeftProperty, (double)pic.X);
            img.SetValue(Canvas.TopProperty, (double)pic.Y);
            img.Opacity = (double)pic.Alpha / 100;
            img.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(img_PreviewMouseLeftButtonDown);
            img.PreviewMouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(img_PreviewMouseLeftButtonUp);
            App.piclist.Add(img);
            return img;
        }

        void img_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            Image img = sender as Image;
            Canvas can = img.Parent as Canvas;
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                img.Opacity = 0.5;
                Point mp = e.MouseDevice.GetPosition(can);
                double nx = mp.X - _x;
                double ny = mp.Y - _y;
                _x = mp.X;
                _y = mp.Y;
                img.SetValue(Canvas.LeftProperty, double.Parse((_imgx + nx).ToString("F0")));
                img.SetValue(Canvas.TopProperty, double.Parse((_imgy + ny).ToString("F0")));
                _imgx += nx;
                _imgy += ny;
            }
        }
        
        /// <summary>
        /// 鼠标松开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void img_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            SaveToImageData((Image)sender, App.dt);
            //App.uiobj = null;
           // Image img = sender as Image;
           // img.MouseMove -= new MouseEventHandler(img_PreviewMouseMove);
           // img.Opacity=objAlpha;
          //  isStyle = "";
          //  SaveToImageData((Image)sender, App.dt);
           // pessCan = null;
        }
        
        /// <summary>
        /// 鼠标按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void img_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
                try
                {
                    DelBindingAll();
                    //MainWindow.workrightuc.DelBindingImg(App.uiobj as Image);
                }
                catch { }
           
            Image pessImg = sender as Image;
            App.uilockobj=App.uiobj = pessImg;
            MainWindow.workrightuc.BindingImg(App.uiobj as Image);
            Press_name = pessImg.Name;
        }

        /// <summary>
        /// 创建一个文本元素
        /// </summary>
        /// <param name="tx"></param>
        /// <param name="canvas"></param>
        public TextBlock CreatText(Text tx, Canvas canvas)
        {
            if (WorkMainAreaUC.myCan != null)
            {
                WorkMainAreaUC.layer.Remove(WorkMainAreaUC.myCan);
            }
            pcan = canvas;
            TextBlock tb = new TextBlock();
            tb.Name = tx.Name;
            tb.Uid = tx.Id;
            List<string> taglist = new List<string>();
            taglist.Add("true");
            taglist.Add("true");
            tb.Tag = taglist;
            tb.Text = tx.Content;
            tb.Width = tx.Width;
            tb.Height = tx.Height;
            tb.SetValue(Canvas.LeftProperty, (double)tx.X);
            tb.SetValue(Canvas.TopProperty, (double)tx.Y);

            if (tx.Align == "left")
            {
                tb.TextAlignment = TextAlignment.Left;
            }
            else if (tx.Align == "right")
            {
                tb.TextAlignment = TextAlignment.Right;
            }
            else if (tx.Align == "center")
            {
                tb.TextAlignment = TextAlignment.Center;
            }
            if (tx.Bold == "true")
            {
                tb.FontWeight = FontWeights.Bold;
            }
            else
            {
                tb.FontWeight =  FontWeights.Normal;
            }
            tb.FontSize = double.Parse(tx.Size);
            tb.Foreground = new SolidColorBrush(ToColor(tx.Color));
            if (tx.Multiline == "true")
            {
                tb.TextWrapping = TextWrapping.Wrap;  //换行
            }
            else
            {
                tb.TextWrapping = TextWrapping.NoWrap;  //换行
            }
            canvas.Children.Add(tb);
            tb.PreviewMouseDown += new System.Windows.Input.MouseButtonEventHandler(tb_PreviewMouseDown);
            tb.PreviewMouseUp += new System.Windows.Input.MouseButtonEventHandler(tb_PreviewMouseUp);
            
            App.textlist.Add(tb);
            return tb;
        }

        void tb_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
           // isStyle = "";
            SaveToTextData((TextBlock)sender, App.dt);
           // App.uiobj = null;
           // pessCan = null;
        }

        void tb_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {   
                try
                {
                    DelBindingAll();
                    //MainWindow.workrightuc.DelBindingImg(App.uiobj as Image);
                }
                catch { }
            TextBlock pessTb = sender as TextBlock;
            Canvas pcan = pessTb.Parent as Canvas;
            App.uilockobj = App.uiobj = pessTb;
            MainWindow.workrightuc.BindingText(App.uiobj as TextBlock);
            Press_name = pessTb.Name;
            //acStyle = isStyle = "Text";
            pessText = (TextBlock)sender;
            //Press_name = pessText.Name;
            //pessCan = pessText.Parent as Canvas;
            ////layer = AdornerLayer.GetAdornerLayer(pcan);
            ////if (myCan != null)
            ////{
            ////    layer.Remove(myCan);
            ////}
            ////myCan = new MyCanvasAdorner(pessText);
            ////layer.Add(myCan);
            //Point point = e.MouseDevice.GetPosition(pessCan);
            //Point pointrect = pessText.TranslatePoint(new Point(0, 0), pessCan);
            //_x = point.X;
            //_y = point.Y;
            //_imgx = pointrect.X;
            //_imgy = pointrect.Y;
            if (e.ClickCount == 2)
            {
                App.uiobj = null;
                WorkMainAreaUC.layer = AdornerLayer.GetAdornerLayer(pcan);
                if (WorkMainAreaUC.myCan != null)
                {
                    WorkMainAreaUC.layer.Remove(WorkMainAreaUC.myCan);
                }
                pessTb.Visibility = Visibility.Hidden;
                AutoSizeRichTextBox txt = new AutoSizeRichTextBox();
                txt.Name = "txtinput";
                txt.Width = pessTb.Width;
                txt.Height = pessTb.Height;
                txt.SetValue(Canvas.LeftProperty, pessTb.GetValue(Canvas.LeftProperty));
                txt.SetValue(Canvas.TopProperty, pessTb.GetValue(Canvas.TopProperty));
                txt.SetValue(Canvas.ZIndexProperty, 100);
                txt.Tag = pessTb;
                FlowDocument fd = new FlowDocument(new Paragraph(new Run(pessTb.Text.TrimEnd())));
                fd.LineHeight=1;
                txt.Document = fd;//new FlowDocument(new Paragraph(new Run(pessText.Text)));
                txt.Height = double.NaN;
                txt.Document.TextAlignment = pessTb.TextAlignment;
                txt.FontWeight = pessTb.FontWeight;
                txt.Foreground = pessTb.Foreground;
                txt.FontSize = pessTb.FontSize;
                txt.Focus();
                //Keyboard..Focus(txt);
               // txt.Select(0, txt.Text.Length);
                txt.SetValue(Panel.ZIndexProperty, 100);
                txt.PreviewMouseDown += new MouseButtonEventHandler(txt_MouseDown);
                txt.TextChanged += new TextChangedEventHandler(txt_TextChanged);
               // txt.LostFocus += new RoutedEventHandler(txt_LostFocus);
                txt.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(txt_LostKeyboardFocus);
                txt.MouseLeave += new MouseEventHandler(txt_MouseLeave);
                txt.MouseEnter+=new MouseEventHandler(txt_MouseEnter);
                // txt.LostKeyboardFocus+=new System.Windows.Input.KeyboardFocusChangedEventHandler(txt_LostFocus);
                pcan.Children.Add(txt);
                autoRTB = txt;
                Keyboard.Focus(txt);
                //layer = AdornerLayer.GetAdornerLayer(pcan);
                //if (myCan != null)
                //{
                //    layer.Remove(myCan);
                //}
               // myCan = new MyCanvasAdorner(pessText);
               // layer.Add(myCan);
                // layer.Remove(myCan);
            }
        }

        void txt_MouseEnter(object sender, MouseEventArgs e)
        {
            isleave = 1;
        }
        public static int isleave = 0;
        void txt_MouseLeave(object sender, MouseEventArgs e)
        {
            isleave = 2;
        }

      

        void txt_MouseDown(object sender, MouseButtonEventArgs e)
        {
            
            ((AutoSizeRichTextBox)sender).Focus();
            ((AutoSizeRichTextBox)sender).AppendText("");
           App.uiobj = null;
        }

        void txt_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            Canvas pcan = ((AutoSizeRichTextBox)sender).Parent as Canvas;
           // TextBlock pessText = App.uilockobj as TextBlock;        
            WorkMainAreaUC.myCan = new MyCanvasAdorner(pessText, false);
            WorkMainAreaUC.layer.Add(WorkMainAreaUC.myCan);
            pessText.Visibility = Visibility.Visible;
            pcan.Children.Remove((AutoSizeRichTextBox)sender);
        }

        void txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            //TextBlock pessText = App.uilockobj as TextBlock;
            TextRange range = new TextRange(((AutoSizeRichTextBox)sender).Document.ContentStart, ((AutoSizeRichTextBox)sender).Document.ContentEnd);
            pessText.Text = range.Text;
            pessText.Width = ((AutoSizeRichTextBox)sender).Width;
            pessText.Height = ((AutoSizeRichTextBox)sender).Height;
        }

        void txt_LostFocus(object sender, RoutedEventArgs e)
        {
            Canvas pcan = ((AutoSizeRichTextBox)sender).Parent as Canvas;
           // TextBlock pessText = App.uilockobj as TextBlock;
            pessText.Visibility = Visibility.Visible;
            //TextRange range = new TextRange(autoRTB.Document.ContentStart, autoRTB.Document.ContentEnd);
            
            //pessText.Text = range.Text;
            //pessText.TextAlignment = autoRTB.Document.TextAlignment;
            
            //autoRTB = null;
          //  Canvas can = ((AutoSizeRichTextBox)sender).Parent as Canvas;
            try
            {
                pcan.Children.Remove((AutoSizeRichTextBox)sender);
            }
            catch { }
        }
        /// <summary>
        /// 创建一个矩形元素
        /// </summary>
        /// <param name="rect"></param>
        /// <param name="canvas"></param>
        public Rectangle CreatRect(CooStationsToolsNew.Model.Rect rect, Canvas canvas)
        {
            if (WorkMainAreaUC.myCan != null)
            {
                WorkMainAreaUC.layer.Remove(WorkMainAreaUC.myCan);
            }
            pcan = canvas;
            Rectangle rt = new Rectangle();
            rt.Name = rect.Name;
            List<string> taglist = new List<string>();
            taglist.Add("true");
            taglist.Add("true");
            rt.Tag = taglist;
            rt.Uid = rect.Id;
            rt.Width = rect.Width;
            rt.Height = rect.Height;
            rt.SetValue(Canvas.LeftProperty, (double)rect.X);
            rt.SetValue(Canvas.TopProperty, (double)rect.Y);
            rt.Fill = new SolidColorBrush(ToColor(rect.RectColor));
            rt.Stroke = new SolidColorBrush(ToColor(rect.LineColor));
            rt.Opacity = (double)rect.RectAlpha / 100;
            rt.StrokeThickness = rect.Border;
            canvas.Children.Add(rt);
            rt.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(rt_PreviewMouseLeftButtonDown);
            rt.PreviewMouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(rt_PreviewMouseLeftButtonUp); 
            App.rectlist.Add(rt);
            return rt;
        }

        /// <summary>
        /// 矩形鼠标松开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void rt_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
           // isStyle = "";
            SaveToRectData((Rectangle)sender, App.dt);
          //  pessCan = null;
            //App.uiobj = null;
        }
        /// <summary>
        /// 矩形鼠标按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void rt_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
                try
                {
                    DelBindingAll();
                }
                catch { }
            Rectangle pessRect = sender as Rectangle;
            App.uilockobj = App.uiobj = pessRect;
            MainWindow.workrightuc.BindingRect(App.uiobj as Rectangle);
            Press_name = pessRect.Name;

            //acStyle = isStyle = "rectangle";
            
            //pessRect = (Rectangle)sender;
            ////pessRect.Tag = true;
            //Press_name = pessRect.Name;
            //pessCan = pessRect.Parent as Canvas;
            ////layer = AdornerLayer.GetAdornerLayer(pcan);
            ////if (myCan != null)
            ////{
            ////    layer.Remove(myCan);
            ////}
            ////myCan = new MyCanvasAdorner(pessRect);
            ////layer.Add(myCan);
            //Point point = e.MouseDevice.GetPosition(pessCan);
            //Point pointrect = pessRect.TranslatePoint(new Point(0, 0), pessCan);
            //_x = point.X;
            //_y = point.Y;
            //_imgx = pointrect.X;
            //_imgy = pointrect.Y;
        }


        public void DelBindingAll()
        {
            try
            {
                MainWindow.workrightuc.DelBindingRect(App.uiobj as Rectangle);
            }
            catch { }
            try
            {
                MainWindow.workrightuc.DelBindingImg(App.uiobj as Image);
            }
            catch { }
            try
            {
                MainWindow.workrightuc.DelBindingDiv(App.uiobj as Canvas);
            }
            catch { }
            try
            {
                MainWindow.workrightuc.DelBindingText(App.uiobj as TextBlock);
            }
            catch { }
        }

        /// <summary>
        /// 创建一个对象集合器
        /// </summary>
        /// <param name="div"></param>
        /// <param name="canvas"></param>
        /// <returns></returns>
        public Canvas CreatDiv(Div div, Canvas canvas)
        {
            if (WorkMainAreaUC.myCan != null)
            {
                WorkMainAreaUC.layer.Remove(WorkMainAreaUC.myCan);
            }
            pcan = canvas;
            Image img = new Image();
            img.Source = new BitmapImage(new Uri("pic/divpoint.png", UriKind.RelativeOrAbsolute));
            img.Width = 15.0;
            img.Height = 15.0;
            List<string> taglist = new List<string>();
            taglist.Add("true");
            taglist.Add("true");
            img.Tag = taglist;
            img.Stretch = Stretch.None;
            img.SetValue(Canvas.LeftProperty, -5.5);
            img.SetValue(Canvas.TopProperty, -5.5);
            Canvas.SetZIndex(img, 100);
            Canvas cv = new Canvas();
            cv.Name = div.Name;
            cv.Uid = div.Id;
            cv.Tag = img;
            cv.Opacity = (double)div.Alpha / 100;
            cv.Width = div.Width;
            cv.Height = div.Height;
            cv.Background = new SolidColorBrush(Colors.Gray);
            cv.Background.Opacity = 0.0;
            cv.SetValue(Canvas.LeftProperty, (double)div.X);
            cv.SetValue(Canvas.TopProperty, (double)div.Y);
            cv.Children.Add(img);
            canvas.Children.Add(cv);
            cv.PreviewMouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(cv_PreviewMouseLeftButtonUp);
            cv.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(cv_PreviewMouseLeftButtonDown);
            cv.MouseEnter += new System.Windows.Input.MouseEventHandler(cv_MouseEnter);
            cv.MouseLeave += new System.Windows.Input.MouseEventHandler(cv_MouseLeave);
            App.divlist.Add(cv);
            return cv;
        }

        void cv_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            Canvas can = (Canvas)sender;
            can.Background.Opacity = 0.0;
        }

        void cv_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
           Canvas can = (Canvas)sender;
           can.Background.Opacity = 0.1;
        }

        void cv_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (autoRTB == null)
            {
                if (App.uiobj != null)
                {
                    try
                    {
                        DelBindingAll();
                        //  MainWindow.workrightuc.DelBindingDiv(App.uiobj as Canvas);
                    }
                    catch { }
                }
                Canvas pessDiv = sender as Canvas;
                App.uilockobj = App.uiobj = pessDiv;
                MainWindow.workrightuc.BindingDiv(App.uiobj as Canvas);
                Press_name = pessDiv.Name;
            }

            //acStyle = isStyle = "Div";
            //targetCan = (Canvas)sender;
            //((Image)targetCan.Tag).Visibility = Visibility.Collapsed;
            //Press_name = targetCan.Name;
            //pessCan = targetCan.Parent as Canvas;
            ////layer = AdornerLayer.GetAdornerLayer(pcan);
            ////if (myCan != null)
            ////{
            ////    layer.Remove(myCan);
            ////}
            ////myCan = new MyCanvasAdorner(targetCan);
            ////layer.Add(myCan);
            //Point point = e.MouseDevice.GetPosition(pessCan);
            //Point pointrect = targetCan.TranslatePoint(new Point(0, 0), pessCan);
            //_x = point.X;
            //_y = point.Y;
            //_imgx = pointrect.X;
            //_imgy = pointrect.Y;
        }

        void cv_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
           // isStyle = "";
            //保存div的方法写这里。
            SaveToDivData((Canvas)sender, App.dt);
          //  App.uiobj = null;
           // pessCan = null;
        }
        /// <summary>
        /// 从div数组中得到一个图片元素
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public Canvas GetDiv(String div)
        {
            for (int i = 0; i < App.divlist.Count; i++)
            {
                Canvas a = (Canvas)App.divlist[i];
                if (a.Uid == div)
                {
                    return a;
                }
            }
            return null;
        }

        /// <summary>
        /// dt数组得到DIV
        /// </summary>
        /// <param name="ca"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public Div GetDiv(Canvas ca, DataTable dt)
        {
            if (ca != null)
            {
                Div Mydiv = null;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        if (div.Name == ca.Name)
                        {
                            Mydiv = div;
                            break;
                        }
                        else
                        {
                            Mydiv = GetDiv(ca, div.Dt);
                            if (Mydiv != null)
                            {
                                break;
                            }
                        }
                    }
                }
                return Mydiv;
            }
            else { return null; }
        }
        /// <summary>
        /// 从DT数组中得到一个PIC对象
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public Text GetText(TextBlock txt, DataTable dt)
        {
            Text Mytext = null;
            if (txt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "text")
                    {
                        Text text = (Text)dt.Rows[i][1];
                        if (text.Name == txt.Name)
                        {
                            Mytext = text;
                            break;
                        }
                    }
                    else if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        Mytext = GetText(txt, div.Dt);
                        if (Mytext != null)
                        {
                            break;
                        }
                    }
                }
            }
            return Mytext;
        }
        /// <summary>
        /// 从DT数组中得到一个PIC对象
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public Pic GetPic(Image img, DataTable dt)
        {
            Pic Mypic = null;
            if (img != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "image")
                    {
                        Pic pic = (Pic)dt.Rows[i][1];
                        if (pic.Name == img.Name)
                        {
                            Mypic = pic;
                            break;
                        }
                    }
                    else if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        Mypic = GetPic(img, div.Dt);
                        if (Mypic != null)
                        {
                            break;
                        }
                    }
                }
            }
            return Mypic;
        }
        /// <summary>
        /// 从图片数组中得到一个图片元素
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public Image GetImage(String img)
        {
            for (int i = 0; i < App.piclist.Count; i++)
            {
                Image a = (Image)App.piclist[i];
                if (a.Uid == img)
                {
                    return a;
                }
            }
            return null;
        }
        /// <summary>
        /// 从数组得到一个RECT对象
        /// </summary>
        /// <param name="Rect"></param>
        /// <returns></returns>
        public CooStationsToolsNew.Model.Rect GetRect(Rectangle Rect, DataTable dt)
        {
            try
            {
                CooStationsToolsNew.Model.Rect Myre = null;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "rect")
                    {
                        CooStationsToolsNew.Model.Rect re = (CooStationsToolsNew.Model.Rect)dt.Rows[i][1];
                        if (re.Name == Rect.Name)
                        {
                            Myre = re;
                            break;
                        }
                    }
                    if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        Myre =  GetRect(Rect, div.Dt);
                        if (Myre != null)
                        { break; }
                    }
                }
                return Myre;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 从矩形数组中得到一个矩形元素
        /// </summary>
        /// <param name="rect"></param>
        /// <returns></returns>
        public Rectangle GetRectangle(String rect)
        {
            for (int i = 0; i < App.rectlist.Count; i++)
            {
                Rectangle a = (Rectangle)App.rectlist[i];
                if (a.Uid == rect)
                {
                    return a;
                }
            }
            return null;
        }

        /// <summary>
        /// 从Text数组中得到一个矩形元素
        /// </summary>
        /// <param name="rect"></param>
        /// <returns></returns>
        public TextBlock GetText(String text)
        {
            for (int i = 0; i < App.textlist.Count; i++)
            {
                TextBlock a = (TextBlock)App.textlist[i];
                if (a.Uid == text)
                {
                    return a;
                }
            }
            return null;
        }
        /// <summary>
        /// 删除某个元素
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="canvas"></param>
        public void DeleteThis(object sender)
        {
           
            if (sender is Image)
            {
                Image a = (Image)sender;
                DeleteImageToDt(a,App.dt);
                DeleteTheTempXml(a.Name, App.appPath + "\\temp\\" + App.pageName + ".xml");
            }
            else if (sender is Rectangle)
            {
                Rectangle re = (Rectangle)sender;
                DeleteRectToDt(re,App.dt);
                DeleteTheTempXml(re.Name, App.appPath + "\\temp\\" + App.pageName + ".xml");
            }
            else if (sender is Canvas)
            {
                Canvas ca = (Canvas)sender;
                DeleteDivToDt(ca,App.dt);
                DeleteTheTempXml(ca.Name, App.appPath + "\\temp\\" + App.pageName + ".xml");
            }
            else if (sender is TextBlock)
            {
                TextBlock tx = (TextBlock)sender;
                DeleteTextToDt(tx, App.dt);
                DeleteTheTempXml(tx.Name, App.appPath + "\\temp\\" + App.pageName + ".xml");
            }
        }

        /// <summary>
        /// 删除XML所有数据
        /// </summary>
        public void DeleteTheTempXmlAll()
        {
            try
            {
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(App.appPath + "\\temp\\" + App.pageName + ".xml");
                XmlNode list = xdoc.ChildNodes[1];
                list.RemoveAll();
                xdoc.Save(App.appPath + "\\temp\\" + App.pageName + ".xml");

            }
            catch { }
        }

        /// <summary>
        /// 数组中删除某text
        /// </summary>
        /// <param name="tx"></param>
        /// <param name="dt"></param>
        private void DeleteTextToDt(TextBlock tx, DataTable dt)
        {
            if (tx != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "text")
                    {
                        Text te = (Text)dt.Rows[i][1];
                        if (te.Name == tx.Name)
                        {
                            dt.Rows.RemoveAt(i);
                            App.textlist.Remove(tx);
                            break;
                        }
                    }
                    if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        DeleteTextToDt(tx, div.Dt);
                    }
                }
            }
        }

        /// <summary>
        /// 数组中删除某Div
        /// </summary>
        /// <param name="ca"></param>
        private void DeleteDivToDt(Canvas ca ,DataTable dt)
        {
            if (ca != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        if (div.Name == ca.Name)
                        {
                            dt.Rows.RemoveAt(i);
                            App.divlist.Remove(ca);
                            break;
                        }
                        else
                        {
                            DeleteDivToDt(ca, div.Dt);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 从数组中删除某矩形
        /// </summary>
        /// <param name="a"></param>
        private void DeleteRectToDt(Rectangle r, DataTable dt)
        {
            if (r != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "rect")
                    {
                        CooStationsToolsNew.Model.Rect re = (CooStationsToolsNew.Model.Rect)dt.Rows[i][1];
                        if (re.Name == r.Name)
                        {
                            dt.Rows.RemoveAt(i);
                            App.rectlist.Remove(r);
                            break;
                        }
                    }
                    if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        DeleteRectToDt(r, div.Dt);
                    }
                }
            }
        }


        /// <summary>
        /// 从数组中删除某个图片
        /// </summary>
        /// <param name="a"></param>
        private void DeleteImageToDt(Image a, DataTable dt)
        {
            if (a != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][0].ToString() == "image")
                    {
                        Pic pic = (Pic)dt.Rows[i][1];
                        if (pic.Name == a.Name)
                        {
                            dt.Rows.RemoveAt(i);
                            App.piclist.Remove(a);
                            break;
                        }
                    }
                    if (dt.Rows[i][0].ToString() == "div")
                    {
                        Div div = (Div)dt.Rows[i][1];
                        DeleteImageToDt(a, div.Dt);
                    }
                }
            }
        }
        /// <summary>
        /// 根据名字查找XML节点删除
        /// </summary>
        /// <param name="name"></param>
        /// <param name="xmlPath"></param>
        /// <returns></returns>
        private bool DeleteTheTempXml(string name, string xmlPath)
        {
            try
            {
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(xmlPath);
                XmlNodeList list = xdoc.ChildNodes[1].ChildNodes;
                delthis(xdoc.ChildNodes[1], list, name);
                xdoc.Save(xmlPath);
                return true;
            }
            catch { return false; }
        }

        /// <summary>
        /// 刪除某个节点元素
        /// </summary>
        private void delthis(XmlNode root, XmlNodeList list, string name)
        {
            foreach (XmlNode xn in list)
            {
                if (xn.Name == "value")
                {
                    return;
                }
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("name") == name)
                {
                    root.RemoveChild(xe);
                }
                else
                {
                    if (xe.HasChildNodes)
                    {
                        delthis(xe, xe.ChildNodes, name);
                    }
                }
            }
        }

        /// <summary>
        /// 删除图片相关的itemid
        /// </summary>
        /// <param name="pic"></param>
        /// <param name="dt"></param>
        private void DeleteImageEventItem(Pic pic, DataTable dt)
        {
            if (pic != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    if (pic.OnClick != null && pic.OnClick != "")
                    {
                        if (dr[0].ToString() == pic.OnClick)
                        {
                            dt.Rows.Remove(dr);
                        }
                    }
                    if (pic.OnRollOut != null && pic.OnRollOut != "")
                    {
                        if (dr[0].ToString() == pic.OnRollOut)
                        {
                            dt.Rows.Remove(dr);
                        }
                    }
                    if (pic.OnRollOver != null && pic.OnRollOver != "")
                    {
                        if (dr[0].ToString() == pic.OnRollOver)
                        {
                            dt.Rows.Remove(dr);
                        }
                    }

                }
            }
        }

        public void DeleteImageEventTarget(Pic pic, DataTable dt)
        {
            if (pic != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    List<ClipAction> actionlist = (List<ClipAction>)dt.Rows[i][1];
                    for (int j = 0; j < actionlist.Count; j++)
                    {
                        ClipAction ca = (ClipAction)actionlist[j];
                        if (ca.TargetId == pic.Id)
                        {

                        }
                    }
                }
            }
        }

        /// <summary>
        /// 设置新建图片的ID
        /// </summary>
        /// <returns></returns>
        internal string SetImageID()
        {
            int[] s = new int[App.piclist.Count];
            for (int i = 0; i < App.piclist.Count; i++)
            {
              string id = App.piclist[i].Uid;
              try
              {
                  string number = id.Substring(5);
                  int b = int.Parse(number);
                  s[i] = b;
              }
              catch 
              {
                 
              }
            }
            fun(1, s);
            return count.ToString();
        }
        /// <summary>
        /// 设置矩形id
        /// </summary>
        /// <returns></returns>
        internal string SetRectID()
        {
            int[] s = new int[App.rectlist.Count];
            for (int i = 0; i < App.rectlist.Count; i++)
            {
                string id = App.rectlist[i].Uid;
                try
                {
                    string number = id.Substring(4);
                    int b = int.Parse(number);
                    s[i] = b;
                }
                catch
                {

                }
            }
            fun(1, s);
            return count.ToString();
        }
        /// <summary>
        /// 设置Divid
        /// </summary>
        /// <returns></returns>
        internal string SetDivID()
        {
            int[] s = new int[App.divlist.Count];
            for (int i = 0; i < App.divlist.Count; i++)
            {
                string id = App.divlist[i].Uid;
                try
                {
                    string number = id.Substring(3);
                    int b = int.Parse(number);
                    s[i] = b;
                }
                catch
                {

                }
            }
            fun(1, s);
            return count.ToString();
        }

        /// <summary>
        /// 设置Textid
        /// </summary>
        /// <returns></returns>
        internal string SetTextID()
        {
            int[] s = new int[App.textlist.Count];
            for (int i = 0; i < App.textlist.Count; i++)
            {
                string id = App.textlist[i].Uid;
                try
                {
                    string number = id.Substring(4);
                    int b = int.Parse(number);
                    s[i] = b;
                }
                catch
                {

                }
            }
            fun(1, s);
            return count.ToString();
        }

        int count = 0;

        public void  fun(int num ,int[] s)
        {
            int  str =  num;
            bool tt = false ;
            for (int i = 0; i < s.Length; i++)
            {
                if (str == s[i])
                {
                    tt = true;
                    break;
                }
            }
            if (tt)
            {
                num++;
                fun(num,s);
            }
            else {
                count = str;
            }
        }

        public void ChangeTheIndex(string move, string moveto, string type)
        {
            object b = GetThe(move, App.dt);
            if (b is Text)
            {
                DataRow dr = App.dt.NewRow();
                dr[0] = "text";
                dr[1] = b;
                if (type == "0")
                {
                    Insert(dr, moveto, App.dt);
                }
                else if (type == "1")
                {
                    InsertInto(dr, moveto, App.dt);
                }
                else
                {
                    InsertTop(dr, App.dt);
                }
            }
            else if (b is Pic)
            {
                DataRow dr = App.dt.NewRow();
                dr[0] = "image";
                dr[1] = b;
                if (type == "0")
                {
                    Insert(dr, moveto, App.dt);
                }
                else if (type == "1")
                {
                    InsertInto(dr, moveto, App.dt);
                }
                else
                {
                    InsertTop(dr, App.dt);
                }
            }
            else if (b is Div)
            {
                DataRow dr = App.dt.NewRow();
                dr[0] = "div";
                dr[1] = b;
                if (type == "0")
                {
                    Insert(dr, moveto, App.dt);
                }
                else if (type == "1")
                {
                    InsertInto(dr, moveto, App.dt);
                }
                else
                {
                    InsertTop(dr, App.dt);
                }
            }
            else if (b is CooStationsToolsNew.Model.Rect)
            {
                DataRow dr = App.dt.NewRow();
                dr[0] = "rect";
                dr[1] = b;
                if (type == "0")
                {
                    Insert(dr, moveto, App.dt);
                }
                else if (type == "1")
                {
                    InsertInto(dr, moveto, App.dt);
                }
                else
                {
                    InsertTop(dr, App.dt);
                }
            }


            GetTheNode(move, moveto, type);
        }

        public void GetTheNode(string Name, string moveto, string type)
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(App.appPath + "//temp//" + App.pageName + ".xml");
            XmlNodeList list = xDoc.ChildNodes[1].ChildNodes;
            XmlNode myNode = GetNode(Name, list);
            if (myNode != null)
            {
                XmlNode newNode = xDoc.ImportNode(myNode, true);

                if (type == "2")
                {
                    xDoc.ChildNodes[1].AppendChild(newNode);
                }
                else
                {
                    intoxml(newNode, moveto, type, list);
                }
                xDoc.Save(App.appPath + "//temp//" + App.pageName + ".xml");
            }
        }
        private XmlNode GetNode(string Name, XmlNodeList list)
        {
            XmlNode myNode = null;
            foreach (XmlNode xn in list)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("name") == Name)
                {
                    myNode = xn;
                    xe.ParentNode.RemoveChild(xn);
                    break;
                }
                if (xe.HasChildNodes)
                {
                    myNode = GetNode(Name, xe.ChildNodes);
                    if (myNode != null)
                    { break; }
                }
            }

            return myNode;
        }

        private void intoxml(XmlNode newNode, string moveto, string type, XmlNodeList list)
        {
            if (type == "0")
            {
                InsertXml(newNode, moveto, list);
            }
            else if (type == "1")
            {
                InsertIntoXml(newNode, moveto, list);
            }

        }
        private void InsertXml(XmlNode node, string moveto, XmlNodeList list)
        {
            foreach (XmlNode xn in list)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("name") == moveto)
                {
                    xn.ParentNode.InsertAfter(node, xn);
                    break;
                }
                if (xe.HasChildNodes)
                {
                    InsertXml(node, moveto, xe.ChildNodes);
                }
            }
        }
        private void InsertIntoXml(XmlNode node, string moveto, XmlNodeList list)
        {
            foreach (XmlNode xn in list)
            {
                XmlElement xe = (XmlElement)xn;
                if (xe.GetAttribute("name") == moveto)
                {
                    xe.AppendChild(node);
                    break;
                }
                if (xe.HasChildNodes)
                {
                    InsertIntoXml(node, moveto, xe.ChildNodes);
                }
            }
        }


        private void InsertInto(DataRow dr, string moveto, DataTable dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i][0].ToString() == "div")
                {
                    Div div = (Div)dt.Rows[i][1];
                    if (div.Name == moveto)
                    {
                        dt.Rows.Add(dr);
                        break;
                    }
                    else
                    {
                        InsertInto(dr, moveto, div.Dt);
                    }
                }

            }
        }

        public void Insert(DataRow dr, string moveto, DataTable dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i][0].ToString() == "image")
                {
                    Pic pic = (Pic)dt.Rows[i][1];
                    if (pic.Name == moveto)
                    {
                        if (i == 0)
                        {
                            dt.Rows.InsertAt(dr, i);
                        }
                        else
                        {
                            dt.Rows.InsertAt(dr, i - 1);
                        }

                        break;
                    }
                } if (dt.Rows[i][0].ToString() == "text")
                {
                    Text pic = (Text)dt.Rows[i][1];
                    if (pic.Name == moveto)
                    {
                        if (i == 0)
                        {
                            dt.Rows.InsertAt(dr, i);
                        }
                        else
                        {
                            dt.Rows.InsertAt(dr, i - 1);
                        }
                        break;
                    }
                } if (dt.Rows[i][0].ToString() == "rect")
                {
                    CooStationsToolsNew.Model.Rect pic = (CooStationsToolsNew.Model.Rect)dt.Rows[i][1];
                    if (pic.Name == moveto)
                    {
                        if (i == 0)
                        {
                            dt.Rows.InsertAt(dr, i);
                        }
                        else
                        {
                            dt.Rows.InsertAt(dr, i - 1);
                        }
                        break;
                    }
                }
                if (dt.Rows[i][0].ToString() == "div")
                {
                    Div div = (Div)dt.Rows[i][1];
                    if (div.Name == moveto)
                    {
                        if (i == 0)
                        {
                            dt.Rows.InsertAt(dr, i);
                        }
                        else
                        {
                            dt.Rows.InsertAt(dr, i - 1);
                        }
                        break;
                    }
                    else
                    {
                        Insert(dr, moveto, div.Dt);
                    }
                }

            }
        }

        private void InsertTop(DataRow dr, DataTable dt)
        {
            dt.Rows.Add(dr);
        }


        public object GetThe(string move, DataTable dt)
        {
            object Mypic = null;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i][0].ToString() == "image")
                {
                    Pic pic = (Pic)dt.Rows[i][1];
                    if (pic.Name == move)
                    {
                        Mypic = pic;
                        dt.Rows.RemoveAt(i);
                        break;
                    }
                } if (dt.Rows[i][0].ToString() == "text")
                {
                    Text pic = (Text)dt.Rows[i][1];
                    if (pic.Name == move)
                    {
                        Mypic = pic;
                        dt.Rows.RemoveAt(i);
                        break;
                    }
                } if (dt.Rows[i][0].ToString() == "rect")
                {
                    CooStationsToolsNew.Model.Rect pic = (CooStationsToolsNew.Model.Rect)dt.Rows[i][1];
                    if (pic.Name == move)
                    {
                        Mypic = pic;
                        dt.Rows.RemoveAt(i);
                        break;
                    }
                }
                if (dt.Rows[i][0].ToString() == "div")
                {
                    Div div = (Div)dt.Rows[i][1];
                    if (div.Name == move)
                    {
                        Mypic = div;
                        dt.Rows.RemoveAt(i);
                        break;
                    }
                    else
                    {
                        Mypic = GetThe(move, div.Dt);
                        if (Mypic != null)
                        {
                            break;
                        }
                    }
                }

            }
            return Mypic;
        }

    }
    internal class AutoSizeRichTextBox : System.Windows.Controls.RichTextBox
    {
        public AutoSizeRichTextBox()
        {
            Height = Double.NaN;//set to nan to enable auto-height
            Loaded += ((sender, args) => AdjustSizeByConent());
        }

        protected override void OnTextChanged(TextChangedEventArgs e)
        {
            base.OnTextChanged(e);
            AdjustSizeByConent();
        }

        public void AdjustSizeByConent()
        {
            var formattedText = GetFormattedText(Document);
            // ReSharper disable ConvertToConstant.Local
            var remainW = 20;
            // ReSharper restore ConvertToConstant.Local

            Width = Math.Min(MaxWidth, Math.Max(MinWidth, formattedText.WidthIncludingTrailingWhitespace + remainW));

        }

        private static FormattedText GetFormattedText(FlowDocument doc)
        {
            var output = new FormattedText(
                GetText(doc),
                CultureInfo.CurrentCulture,
                doc.FlowDirection,
                new Typeface(doc.FontFamily, doc.FontStyle, doc.FontWeight, doc.FontStretch),
                doc.FontSize,
                doc.Foreground);

            int offset = 0;

            foreach (TextElement textElement in GetRunsAndParagraphs(doc))
            {
                var run = textElement as Run;

                if (run != null)
                {
                    int count = run.Text.Length;

                    output.SetFontFamily(run.FontFamily, offset, count);
                    output.SetFontSize(run.FontSize, offset, count);
                    output.SetFontStretch(run.FontStretch, offset, count);
                    output.SetFontStyle(run.FontStyle, offset, count);
                    output.SetFontWeight(run.FontWeight, offset, count);
                    output.SetForegroundBrush(run.Foreground, offset, count);
                    output.SetTextDecorations(run.TextDecorations, offset, count);

                    offset += count;
                }
                else
                {
                    offset += Environment.NewLine.Length;
                }
            }




            return output;
        }

        private static IEnumerable<TextElement> GetRunsAndParagraphs(FlowDocument doc)
        {
            for (TextPointer position = doc.ContentStart;
                position != null && position.CompareTo(doc.ContentEnd) <= 0;
                position = position.GetNextContextPosition(LogicalDirection.Forward))
            {
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementEnd)
                {
                    var run = position.Parent as Run;

                    if (run != null)
                    {
                        yield return run;
                    }
                    else
                    {
                        var para = position.Parent as Paragraph;

                        if (para != null)
                        {
                            yield return para;
                        }
                        else
                        {
                            var lineBreak = position.Parent as LineBreak;

                            if (lineBreak != null)
                            {
                                yield return lineBreak;
                            }
                        }
                    }
                }
            }
        }

        private static string GetText(FlowDocument doc)
        {
            var sb = new StringBuilder();

            foreach (TextElement text in GetRunsAndParagraphs(doc))
            {
                var run = text as Run;
                sb.Append(run == null ? Environment.NewLine : run.Text);
            }

            return sb.ToString();
        }


    }
}
